import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useOrderStore = defineStore('order', () => {
  const STORAGE_KEY = 'erppos_orders'
  const orders = ref([])

  const persist = () => localStorage.setItem(STORAGE_KEY, JSON.stringify(orders.value))

  const initialize = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    if (cached) {
      orders.value = JSON.parse(cached)
      return
    }
    orders.value = []
    persist()
  }

  const todayStr = () => new Date().toISOString().slice(0,10)

  const statsToday = computed(() => {
    const today = todayStr()
    const list = orders.value.filter(o => (o.createdAt || '').startsWith(today))
    return {
      todayOrders: list.length,
      todayAmount: list.reduce((s, x) => s + Number(x.amount || 0), 0),
      toShip: list.filter(x => x.status === '已支付' || x.status === '待发货').length,
      refunding: list.filter(x => x.status === '退款中').length,
    }
  })

  const filtered = (filters = {}) => {
    const s = (filters.search || '').toLowerCase()
    const status = filters.status || ''
    const [start, end] = filters.range || []
    return orders.value.filter(o => {
      if (s && !(o.sn||'').toLowerCase().includes(s) && !(o.buyer||'').toLowerCase().includes(s)) return false
      if (status && o.status !== status) return false
      if (start || end) {
        const d = (o.createdAt || '').slice(0,10)
        if (start && d < start) return false
        if (end && d > end) return false
      }
      return true
    })
  }

  const genSn = () => {
    const date = todayStr().replace(/-/g,'')
    const seq = String(Date.now()).slice(-6)
    return `SO${date}${seq}`
  }

  const createOrder = ({ buyer, items, operator = '系统', channel = '线下' }) => {
    const now = new Date().toISOString()
    const amount = items.reduce((s, it) => s + Number(it.price || 0) * Number(it.qty || 0), 0)
    const order = {
      id: 'O' + Date.now(),
      sn: genSn(),
      createdAt: now,
      buyer: buyer || '散客',
      amount: Number(amount.toFixed(2)),
      status: '待支付',
      channel,
      operator,
      items,
      history: [{ status: '待支付', time: now, note: '创建订单' }]
    }
    orders.value.unshift(order)
    persist()
    return order
  }

  const setStatus = (orderId, status, note = '') => {
    const o = orders.value.find(x => x.id === orderId)
    if (!o) return null
    const now = new Date().toISOString()
    o.status = status
    o.history.push({ status, time: now, note })
    if (status === '已支付') o.paidAt = now
    if (status === '已发货') o.shippedAt = now
    if (status === '已完成') o.completedAt = now
    if (status === '已取消') o.canceledAt = now
    if (status === '已退款') o.refundedAt = now
    persist()
    return o
  }

  const exportOrders = (list = null) => {
    const exportList = list || orders.value
    const headers = ['单号','日期','买家','金额','状态','渠道','操作员']
    const rows = exportList.map(o => [o.sn, o.createdAt, o.buyer, o.amount, o.status, o.channel || '', o.operator || ''])
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    link.href = URL.createObjectURL(blob)
    link.download = `订单_${todayStr()}.csv`
    link.click()
  }

  return {
    orders,
    initialize,
    statsToday,
    filtered,
    createOrder,
    setStatus,
    exportOrders,
  }
})


